# coding:utf-8
# dao_csdn_articles.py
"""
dao for table csdn_articles
:author: antony zhao
:date: 31/3/2020
"""
import logging
import urllib.parse

from config import database_conf
import pymysql


class DaoCsdnArticles:

    def __init__(self):
        self.db = pymysql.connect(host=database_conf.host, user=database_conf.user_name,
                                  password=database_conf.psw, port=database_conf.port,
                                  database=database_conf.database,
                                  charset=database_conf.charset,
                                  cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.db.cursor()

    def set_article_info(self, article_info: {}):
        """
        store article info to mysql
        :return: is it successful? True or False
        """
        article_body = article_info["article_body"].encode()
        print(article_body)
        print(article_body.decode())
        sql = "INSERT INTO csdn_articles(title, article_des, [date], page_view, comments_count, href, article_id, " \
              "article_body) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (
                  article_info["title"], article_info["article_des"], article_info["date"], article_info["page_view"],
                  article_info["comments_count"], article_info["href"], article_info["id"],
                  article_body)
        try:
            self.cursor.execute(sql)
            self.db.commit()
        except Exception as error:
            logging.info("insert to mysql failed, error msg is %s !" % error)
            return False
        return True

    def get_article_info_by_article_id(self):
        # article_info= ArticleInfo()
        # article_info.id = article_id
        sql = "SELECT * FROM csdn_articles"
        self.cursor.execute(sql)
        data = self.cursor.fetchall()
        return data


# just for test
if __name__ == '__main__':
    dao_csdn_articles = DaoCsdnArticles()
    print(dao_csdn_articles.get_article_info_by_article_id())
